<script setup lang='ts'>
import type { VxeGridProps, VxeTableInstance } from 'vxe-table'

import { useGetPricingReportList, useGetRateByProductId, useGetSupplierReport } from '@fl/api/purchase'
import { SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import NP from 'number-precision'
import { useRoute } from 'vue-router'

const props = defineProps<{
    productId: string
}>()

const route = useRoute()

const visible = defineModel<boolean>('visible', { required: true })

const dialogTitle = '项目造价汇总'

const { productId } = toRefs(props)
const getProductId = computed(() => {
    return route.query?.supplierId ? '' : productId.value
})
const getSupplierReportParams = computed(() => ({
    productId: productId.value,
    projectId: route.query.projectId as string,
    supplierId: route.query.supplierId as string,
}))

const { data: pricingReportListData, isLoading: isGetPricingReportListLoading } = useGetPricingReportList(getProductId)
const { data: rateData, isLoading: isGetRateByProductIdLoading } = useGetRateByProductId(getProductId)
const { data: supplierReportData, isLoading: isGetSupplierReportLoading } = useGetSupplierReport(getSupplierReportParams)

// #region Collect Table
const isCollectTableLoading = computed(() => isGetRateByProductIdLoading.value || isGetSupplierReportLoading.value)
const collectTableData = ref<any[]>([])

const collectGridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columns: [
        { field: 'mgmtRate', slots: { default: 'mgmt_rate' }, title: '管理费率' },
        { field: 'mgmtFee', slots: { default: 'mgmt_fee' }, title: '管理费' },
        { field: 'profit', slots: { default: 'profit' }, title: '利润率' },
        { field: 'profitAmount', slots: { default: 'profit_amount' }, title: '利润额' },
        { field: 'rate', slots: { default: 'rate' }, title: '税率' },
        { field: 'taxes', slots: { default: 'taxes' }, title: '税金' },
        { field: 'totalQuote', slots: { default: 'total_quote' }, title: '除税价' },
        { field: 'taxIncludedPrice', slots: { default: 'tax_included_price' }, title: '含税价' },
        // { field: 'taxIncludedUnitPrice', slots: { default: 'tax_included_unit_price' }, title: '含税综合单价' },
    ],
    headerRowClassName: 'bg-white text-[#86909C] text-[14px]',
    height: undefined,
})
// #endregion

// #region Compose Table
const isComposeTableLoading = computed(() => isGetPricingReportListLoading.value)
const composeTableRef = ref<VxeTableInstance>()
const composeTableData = ref<any[]>([])

const composeGridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'categoryName', title: '名称', treeNode: true },
        { field: 'model', title: '规格型号' },
        { field: 'usage', title: '计算用量' },
        { field: 'unit', title: '单位' },
        { field: 'price', slots: { default: 'price' }, title: '综合单价' },
        { field: 'taxFreeTotalPrice', slots: { default: 'tax_free_total_price' }, title: '税前总价' },
        // { field: 'costProportion', title: '造价占比' },
    ],
    headerRowClassName: 'text-[#86909C] text-[14px]',
    height: undefined,
    treeConfig: { expandAll: true, parentField: 'parentId', rowField: 'id' },
})
// #endregion

// #region UI Listener
function cancel() {
    visible.value = false
}

function closed() {

}

function opened() {
    const $composeTable = (composeTableRef.value as any)?.tableInstance
    if ($composeTable) {
        $composeTable.setAllTreeExpand(true)
    }
}
// #endregion

function computePrice(row: any, rate: number) {
    return NP.round(Number(row.taxFreeTotalPrice) * Number(rate) / 100, 4)
}

function computeTaxes(row: any) {
    const mgmtFee = computePrice(row, row.mgmtRate)
    const profitAmount = computePrice(row, row.profit)
    return NP.round((row.taxFreeTotalPrice + mgmtFee + profitAmount) * Number(row.rate) / 100, 4)
}

function computeTotalQuote(row: any) {
    const mgmtFee = computePrice(row, row.mgmtRate)
    const profitAmount = computePrice(row, row.profit)
    return NP.round(row.taxFreeTotalPrice + mgmtFee + profitAmount, 4)
}

function computeTaxIncludedPrice(row: any) {
    const taxes = computeTaxes(row)
    const mgmtFee = computePrice(row, row.mgmtRate)
    const profitAmount = computePrice(row, row.profit)
    return NP.round(taxes + mgmtFee + profitAmount + row.taxFreeTotalPrice, 4)
}

function displayPrice(num: number) {
    if (Number.isNaN(num)) {
        return '-'
    }
    return `${num}元`
}

watchEffect(() => {
    if (supplierReportData.value) {
        const { children, totalQuote, ...rest } = supplierReportData.value
        collectTableData.value = [{
            ...rest,
            taxFreeTotalPrice: totalQuote,
        }]
        composeTableData.value = cloneDeep(children)
    }
    else {
        collectTableData.value = [{
            ...cloneDeep(rateData.value),
            taxFreeTotalPrice: pricingReportListData.value?.[0]?.taxFreeTotalPrice,
        }]
        composeTableData.value = cloneDeep(pricingReportListData.value)
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                close-on-press-escape
                width="1300"
                :has-footer="false"
                @cancel="cancel"
                @closed="closed"
                @opened="opened"
    >
        <div class="h-700 overflow-y-auto">
            <span class="text-[20px] font-semibold">单价汇总</span>

            <SearchTable class="mb-10"
                         v-bind="collectGridOptions"
                         :loading="isCollectTableLoading"
                         :data="collectTableData"
            >
                <template #total_quote="{ row }">
                    <span class="inline-block text-left">{{ displayPrice(computeTotalQuote(row)) }}</span>
                </template>

                <template #rate="{ row }">
                    <span class="inline-block text-left">{{ row.rate }}%</span>
                </template>

                <template #taxes="{ row }">
                    <span class="inline-block text-left">{{ displayPrice(computeTaxes(row)) }}</span>
                </template>

                <template #mgmt_rate="{ row }">
                    <span class="inline-block text-left">{{ row.mgmtRate }}%</span>
                </template>

                <template #mgmt_fee="{ row }">
                    <span class="inline-block text-left">{{ displayPrice(computePrice(row, row.mgmtRate)) }}</span>
                </template>

                <template #profit="{ row }">
                    <span class="inline-block text-left">{{ row.profit }}%</span>
                </template>

                <template #profit_amount="{ row }">
                    <span class="inline-block text-left">{{ displayPrice(computePrice(row, row.profit)) }}</span>
                </template>

                <template #tax_included_price="{ row }">
                    <span class="text-[#dA0004]">{{ displayPrice(computeTaxIncludedPrice(row)) }}</span>
                </template>

                <!-- <template #tax_included_unit_price="{ row }">
                    <span class="text-[#dA0004]">{{ row.taxIncludedUnitPrice }}</span>
                </template> -->
            </SearchTable>

            <span class="text-[20px] font-semibold">单价组成</span>

            <SearchTable v-bind="composeGridOptions"
                         ref="composeTableRef"
                         class="mt-10"
                         :loading="isComposeTableLoading"
                         :data="composeTableData"
            >
                <template #tax_free_total_price="{ row }">
                    <span v-if="!Number.isNaN(Number.parseFloat(row?.taxFreeTotalPrice))"
                          class="text-[#dA0004]"
                    >
                        {{ row.taxFreeTotalPrice }}元
                    </span>

                    <span v-else-if="!Number.isNaN(Number.parseFloat(row?.totalQuote))"
                          class="text-[#dA0004]"
                    >
                        {{ row.totalQuote }}元
                    </span>
                </template>

                <template #price="{ row }">
                    <span v-if="!Number.isNaN(Number.parseFloat(row?.price))"
                          class="text-[#dA0004]"
                    >
                        {{ row.price }}元
                    </span>

                    <span v-else-if="!Number.isNaN(Number.parseFloat(row?.quote))"
                          class="text-[#dA0004]"
                    >
                        {{ row.quote }}元
                    </span>
                </template>
            </SearchTable>
        </div>
    </PlusDialog>
</template>

<style scoped lang="scss">
:deep(.vxe-table--body-wrapper) {
    min-height: 48px !important;
}

:deep(.vxe-grid--toolbar-wrapper) {
    display: none;
}
</style>
